﻿#region
/**
 * $Date: 0001/1/1
*/
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using BuXiaChu.OrderDishes.DAL.DataAccess;
using BuXiaChu.OrderDishes.Model;
#endregion

namespace BuXiaChu.OrderDishes.DAL
{
    public class RolesDAL
    {
        #region private const
        private const string PARAM_ROLE_ID = "@RoleId";
        private const string PARAM_APPLICATION_ID = "@ApplicationId";
        private const string PARAM_NAME = "@Name";
        private const string PARAM_DESCRIPTION = "@Description";

        private static readonly string ConnectionString = SQLHelper.CONNECTION_STRING;
        #endregion

        private static void FillModelFrom(SqlDataReader reader, RolesModel obj)
        {
            #region
            if (reader != null && !reader.IsClosed)
            {
                obj.RoleId = reader.IsDBNull(reader.GetOrdinal("RoleId")) ? Guid.NewGuid() : reader.GetGuid(reader.GetOrdinal("RoleId"));
                obj.ApplicationId = reader.IsDBNull(reader.GetOrdinal("ApplicationId")) ? Guid.NewGuid() : reader.GetGuid(reader.GetOrdinal("ApplicationId"));
                obj.Name = reader.IsDBNull(reader.GetOrdinal("Name")) ? String.Empty : reader.GetString(reader.GetOrdinal("Name"));
                obj.Description = reader.IsDBNull(reader.GetOrdinal("Description")) ? String.Empty : reader.GetString(reader.GetOrdinal("Description"));
            }
            #endregion
        }

        private static SqlParameter[] GetRolesParams(RolesModel obj)
        {
            #region
            SqlParameter[] dbParams ={					
					 SQLHelper.MakeParam(PARAM_ROLE_ID, SqlDbType.UniqueIdentifier,0,obj.RoleId),
					 SQLHelper.MakeParam(PARAM_APPLICATION_ID, SqlDbType.UniqueIdentifier,0,obj.ApplicationId),
					 SQLHelper.MakeParam(PARAM_NAME, SqlDbType.NVarChar, 50,obj.Name),					
					 SQLHelper.MakeParam(PARAM_DESCRIPTION, SqlDbType.NVarChar, 256,obj.Description)					
			};

            return dbParams;
            #endregion
        }

        public static bool Save(RolesModel obj)
        {
            #region
            try
            {
                SqlParameter[] dbParams = GetRolesParams(obj);

                if (obj.RoleId == Guid.Empty)
                {
                    var result = SQLHelper.ExecuteScalar(ConnectionString, CommandType.StoredProcedure, "Roles_Insert", dbParams);
                    if (result != null)
                    {
                        obj.RoleId = new Guid(result.ToString());
                    }
                    return obj.RoleId != Guid.Empty ? true : false;
                }
                else
                {
                    var affectNum = SQLHelper.ExecuteNonQuery(ConnectionString, CommandType.StoredProcedure, "Roles_Update", dbParams);
                    return affectNum > 0 ? true : false;
                }
            }
            catch (Exception e)
            {
                Exception ex = new Exception("Roles-->InsertOrUpdate-->" + e.Message);

                ExceptionMessageDAL.Record(ex);
            }

            return false;
            #endregion
        }

        public static RolesModel GetByRolesId(Guid roleId)
        {
            #region
            SqlDataReader reader = null;
            RolesModel obj = new RolesModel();

            try
            {
                SqlParameter[] dbParams = {
                        SQLHelper.MakeParam(PARAM_ROLE_ID, SqlDbType.Int, 0, roleId)
                    };

                reader = SQLHelper.ExecuteReader(ConnectionString, CommandType.StoredProcedure, "Roles_GetByRoleId", dbParams);

                if (reader.Read())
                {
                    FillModelFrom(reader, obj);
                }
            }
            catch (Exception e)
            {
                Exception ex = new Exception("Roles-->GetSingleObject-->" + e.Message);

                ExceptionMessageDAL.Record(ex);
            }
            finally
            {
                if (reader != null && !reader.IsClosed)
                    reader.Close();
            }

            return obj;
            #endregion
        }

        public static List<RolesModel> GetApplicationId(Guid ApplicationId)
        {
            #region
            SqlDataReader reader = null;
            List<RolesModel> result = new List<RolesModel>();

            try
            {
                SqlParameter[] dbParams = {
                        SQLHelper.MakeParam(PARAM_APPLICATION_ID, SqlDbType.UniqueIdentifier, 0, ApplicationId)
                    };

                reader = SQLHelper.ExecuteReader(ConnectionString, CommandType.StoredProcedure, "Roles_GetByApplicationId", dbParams);

                while (reader.Read())
                {
                    RolesModel obj = new RolesModel();
                    FillModelFrom(reader, obj);

                    result.Add(obj);
                }
            }
            catch (Exception e)
            {
                Exception ex = new Exception("Roles-->GetApplicationId-->" + e.Message);

                ExceptionMessageDAL.Record(ex);
            }
            finally
            {
                if (reader != null && !reader.IsClosed)
                    reader.Close();
            }

            return result;
            #endregion
        }

        public static List<RolesModel> GetAll()
        {
            #region
            SqlDataReader reader = null;
            List<RolesModel> result = new List<RolesModel>();

            try
            {
                reader = SQLHelper.ExecuteReader(ConnectionString, CommandType.Text, "select * from Roles", null);

                while (reader.Read())
                {
                    RolesModel obj = new RolesModel();
                    FillModelFrom(reader, obj);

                    result.Add(obj);
                }
            }
            catch (Exception e)
            {
                Exception ex = new Exception("Roles-->GetApplicationId-->" + e.Message);

                ExceptionMessageDAL.Record(ex);
            }
            finally
            {
                if (reader != null && !reader.IsClosed)
                    reader.Close();
            }

            return result;
            #endregion
        }

        public static Dictionary<int, List<RolesModel>> GetRoleListBySysUserIds(string sysUserIds)
        {
            #region
            SqlDataReader reader = null;
            Dictionary<int, List<RolesModel>> result = new Dictionary<int, List<RolesModel>>();

            try
            {
                SqlParameter[] dbParams = new SqlParameter[]{
                    SQLHelper.MakeParam("@SystemUserIds",SqlDbType.NVarChar,0,sysUserIds)
                };
                reader = SQLHelper.ExecuteReader(ConnectionString, CommandType.StoredProcedure, "SysUserInRoles_GetBySysUserIdList", dbParams);
                var SystemUserId = 0;
                while (reader.Read())
                {
                    SystemUserId = reader.IsDBNull(reader.GetOrdinal("SystemUserId")) ? 0 : reader.GetInt32(reader.GetOrdinal("SystemUserId"));

                    RolesModel obj = new RolesModel();
                    FillModelFrom(reader, obj);

                    if (result.ContainsKey(SystemUserId))
                    {
                        result[SystemUserId].Add(obj);
                    }
                    else
                    {
                        var rolesList = new List<RolesModel>();
                        rolesList.Add(obj);
                        result.Add(SystemUserId,rolesList);
                    }
                }
            }
            catch (Exception e)
            {
                Exception ex = new Exception("Roles-->GetRoleListBySysUserIds-->" + e.Message);

                ExceptionMessageDAL.Record(ex);
            }
            finally
            {
                if (reader != null && !reader.IsClosed)
                    reader.Close();
            }

            return result;
            #endregion
        }

        public static List<RolesModel> GetListBySysUserId(int sysUserId)
        {
            #region
            SqlDataReader reader = null;
            List<RolesModel> result = new List<RolesModel>();

            try
            {
                SqlParameter[] dbParams = new SqlParameter[]{
                    SQLHelper.MakeParam("@SystemUserId",SqlDbType.Int,0,sysUserId)
                };
                reader = SQLHelper.ExecuteReader(ConnectionString, CommandType.StoredProcedure, "SysUserInRoles_GetBySysUserId", dbParams);

                while (reader.Read())
                {
                    RolesModel obj = new RolesModel();
                    FillModelFrom(reader, obj);

                    result.Add(obj);
                }
            }
            catch (Exception e)
            {
                Exception ex = new Exception("Roles-->GetListBySysUserId-->" + e.Message);

                ExceptionMessageDAL.Record(ex);
            }
            finally
            {
                if (reader != null && !reader.IsClosed)
                    reader.Close();
            }

            return result;
            #endregion
        }

        public static bool AddRolesToSysUser(Guid roleId, int sysUserId)
        {
            #region
            try
            {
                SqlParameter[] dbParams = {
                        SQLHelper.MakeParam(PARAM_ROLE_ID, SqlDbType.UniqueIdentifier, 0, roleId),
                         SQLHelper.MakeParam("@SystemUserId", SqlDbType.Int, 0, sysUserId)
                    };

                return SQLHelper.ExecuteNonQuery(ConnectionString, CommandType.StoredProcedure, "SysUserInRoles_Insert", dbParams) > 0 ? true : false;
            }
            catch (Exception e)
            {
                Exception ex = new Exception("Roles-->Delete-->" + e.Message);

                ExceptionMessageDAL.Record(ex);
            }
            return false;
            #endregion
        }

        public static bool Delete(Guid roleId)
        {
            #region
            try
            {
                SqlParameter[] dbParams = {
                        SQLHelper.MakeParam(PARAM_ROLE_ID, SqlDbType.Int, 0, roleId)
                    };

                return SQLHelper.ExecuteNonQuery(ConnectionString, CommandType.StoredProcedure, "Roles_Delete", dbParams) > 0 ? true : false;
            }
            catch (Exception e)
            {
                Exception ex = new Exception("Roles-->Delete-->" + e.Message);

                ExceptionMessageDAL.Record(ex);
            }
            return false;
            #endregion
        }
    }
}
